package com.knowledge.plus.io.AIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 异步非阻塞I/O
 *
 * @author TPF
 * @since 2025/6/4
 */
public class AioServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open()
                .bind(new InetSocketAddress(8080));

        // 异步接收连接（非阻塞）
        server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {
            @Override
            public void completed(AsynchronousSocketChannel client, Void attachment) {
                server.accept(null, this); // 继续接收下一个连接

                ByteBuffer buffer = ByteBuffer.allocate(1024);
                // 异步读取数据（非阻塞）
                client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer buf) {
                        if (result == -1) return;
                        buf.flip();
                        byte[] data = new byte[buf.remaining()];
                        buf.get(data);
                        System.out.println("收到消息: " + new String(data));

                        // 异步回写响应（非阻塞）
                        client.write(ByteBuffer.wrap("[ACK]".getBytes()));
                        buf.clear();
                        client.read(buf, buf, this); // 继续监听读取
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer buf) {
                        System.out.println("读取失败: " + exc.getMessage());
                    }
                });
            }

            @Override
            public void failed(Throwable exc, Void attachment) {
                System.out.println("连接接收失败: " + exc.getMessage());
            }
        });

        System.out.println("AIO服务端已启动");
        Thread.currentThread().join(); // 防止主线程退出
    }
}

